<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import CodeEditor from '../components/CodeEditor.vue'
import httpClient from '../utils/http'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 定义接口详情的类型
interface MockDetail {
  id: string
  name: string
  url: string
  method: string
  status_code: number
  body: Record<string, any>
}

// Mock 接口详情数据 - 初始值
const initialMockDetail: MockDetail = {
  id: '',
  name: '',
  url: '',
  method: 'GET',
  status_code: 200,
  body: {},
}

const mockForm = ref<MockDetail>({...initialMockDetail})

// 用于CodeEditor的响应式变量
const bodyString = ref('')

// 更新body值的函数
const updateBody = (value: string) => {
  try {
    mockForm.value.body = JSON.parse(value)
  } catch (error) {
    console.error('解析body失败:', error)
    // 如果解析失败，保持原有body不变，而不是设置为空对象
    // mockForm.value.body = {}
  }
}

// 监听mockForm.body的变化，仅在初始化时更新bodyString
watch(() => mockForm.value.body, (newVal, oldVal) => {
  // 只有当bodyString为空且有新的body值时才更新
  if (!bodyString.value && newVal) {
    try {
      bodyString.value = JSON.stringify(newVal, null, 2)
    } catch (error) {
      console.error('序列化body失败:', error)
      bodyString.value = '{}'
    }
  }
}, { immediate: true })

// 获取 Mock 接口详情
const fetchMockDetail = async () => {
  try {
    // 确保路由参数 id 存在
    console.log('路由参数:', route.params)
    if (!route.params.id) {
      console.error('缺少接口 ID 参数')
      return
    }
    
    console.log('请求ID:', route.params.id)
    const response = await httpClient.get(`/v1/mocs/${route.params.id}`)
    
    console.log('API响应:', response)
    
    // 检查响应结构
    if (response?.data?.success && response.data.data) {
      console.log('API返回数据:', response.data.data)
      
      // 合并数据，确保所有字段都被覆盖
      mockForm.value = {
        ...initialMockDetail,
        ...response.data.data
      }
      
      console.log('合并后的mockForm:', mockForm.value)
      console.log('mockForm.value.body:', mockForm.value.body)
      
      // 手动触发bodyString更新
      try {
        bodyString.value = JSON.stringify(mockForm.value.body, null, 2)
        console.log('更新后的bodyString:', bodyString.value)
      } catch (error) {
        console.error('序列化body失败:', error)
        bodyString.value = '{}'
      }
    } else {
      console.error('接口返回格式不正确:', response)
    }
  } catch (error) {
    console.error('获取接口详情失败:', error)
  }
}

onMounted(() => {
  fetchMockDetail()
})

const methods = ref(['GET', 'POST', 'PUT', 'DELETE'])

const submitForm = async () => {
  // 显示确认对话框
  const confirmResult = window.confirm('确定要更新这个 Mock 接口吗?')
  if (!confirmResult) return

  // 提交表单逻辑
  console.log('更新 Mock 接口:', mockForm.value)
  
  // 构造符合要求的数据格式
  const requestData = {
    name: mockForm.value.name,
    url: mockForm.value.url,
    method: mockForm.value.method,
    headers: { "Content-Type": "application/json" },
    body: mockForm.value.body,
    status_code: mockForm.value.status_code
  }
  
  try {
    // 发送更新请求到指定的URL
    const response = await httpClient.put(`/v1/mocs/${mockForm.value.id}`, requestData)
    
    // 检查响应结构
    if (response?.data?.success) {
      console.log('更新成功:', response.data)
      ElMessage.success('编辑接口成功')
      // 更新成功后跳转到列表页
      router.push('/')
    } else {
      // 处理失败响应
      const errorMsg = response?.data?.msg || '未知错误'
      const errorCode = response?.data?.code || response?.status || '未知状态码'
      console.error('更新失败:', response)
      alert(`更新失败: ${errorMsg} (错误代码: ${errorCode})`)
    }
  } catch (error: any) {
    // 处理网络错误或其他异常
    console.error('更新接口失败:', error)
    
    // 检查是否有响应数据（如500错误）
    if (error?.response) {
      const errorMsg = error.response?.data?.msg || error.response?.statusText || '服务器内部错误'
      const errorCode = error.response?.data?.code || error.response?.status || '未知状态码'
      alert(`更新接口失败: ${errorMsg} (错误代码: ${errorCode})`)
    } else {
      const errorMsg = error?.message || '网络错误或服务器无响应'
      alert(`更新接口失败: ${errorMsg}`)
    }
  }
}
</script>

<template>
  <div class="mock-edit">
    <h1>编辑 Mock 接口</h1>
    <el-form :model="mockForm" label-width="120px">
      <el-form-item label="接口名称">
        <el-input v-model="mockForm.name" />
      </el-form-item>
      <el-form-item label="URL">
        <el-input v-model="mockForm.url" />
      </el-form-item>
      <el-form-item label="方法">
        <el-select v-model="mockForm.method" placeholder="选择方法">
          <el-option
            v-for="method in methods"
            :key="method"
            :label="method"
            :value="method"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态码">
        <el-input v-model="mockForm.status_code" />
      </el-form-item>
      <strong>响应内容:</strong>
      <div class="response-content">
        <CodeEditor 
          v-model="bodyString"
          language="json" 
          style="height: 400px"
          @update:modelValue="updateBody"
        />
      </div>

      <el-form-item>
        <el-button type="primary" @click="submitForm">更新</el-button>
        <el-button @click="router.push('/')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.mock-edit {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.response-content {
  max-width: 100%;
  overflow-x: auto;
  text-align: left;
}
</style>